package com.lanyou.esb.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.service.security.UserSessionService;
import com.lanyou.cook.util.DateUtil;
import com.lanyou.esb.datadictionary.ForwardStatus;
import com.lanyou.esb.entity.Routing;
import com.lanyou.esb.entity.StoreForward;
import com.lanyou.esb.repository.StoreForwardRepository;
import com.lanyou.esb.web.param.StoreForwardParam;

@RestController
@RequestMapping(Constants.BASE_URL_API + "/storeForwards")
public class StoreForwardController{
	
	@Autowired
	private UserSessionService userSessionService; 
	
	@Autowired
	private StoreForwardRepository storeForwardRepository;
	
	@RequestMapping("/search/findByExample")
	public Page<StoreForward> findByExample(StoreForwardParam param, Pageable pageable) {
		
		Specification<StoreForward> spec = new Specification<StoreForward>() {
			@Override
			public Predicate toPredicate(Root<StoreForward> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicatesList = new ArrayList<>();
				if (StringUtils.isNotBlank(param.getFieldId())) {
					predicatesList.add(
							cb.like(root.get("system").get("field").get("id"),  param.getFieldId()));
				}
				
				if (StringUtils.isNotBlank(param.getIfName())) {
					predicatesList
							.add(cb.like(root.get("interfaceName"), '%' + param.getIfName() + '%'));
				}

				if (StringUtils.isNotBlank(param.getStatus())) {
					predicatesList.add(cb.like(root.get("forwardState"),  param.getStatus() ));
				}
				
				// 领域系统
				Path<String> pathOwnerFieldSystemId = root.get("system").get("id");
				if (StringUtils.isNotBlank(param.getSystemId())) {
					predicatesList.add(cb.equal(root.get("system").get("id"), param.getSystemId()));
				} else {
					// 默认查当前登录用户所管理的领域系统
					Collection<String> fieldSystemIds = userSessionService
							.findFieldSystemIdsOfCurrentAuthenticatedUserCanManage();
					if (!CollectionUtils.isEmpty(fieldSystemIds)) {
						predicatesList.add(pathOwnerFieldSystemId.in(fieldSystemIds));
					} else {
						predicatesList.add(cb.notEqual(cb.literal(1), 1));
					}
				}

				// 纠正错误的时间参数
				DynaBean fixedDates = DateUtil.fixBeginTimeAndEndTime(param.getBeginTime(),
						param.getEndTime());
				Date fixedBeginTime = (Date) fixedDates.get("begin");
				Date fixedEndTime = (Date) fixedDates.get("end");

				Path<Date> pathDate = root.get("forwardDate");
				predicatesList.add(cb.or(cb.isNull(pathDate), cb.between(pathDate, fixedBeginTime, fixedEndTime)));

				query.where(predicatesList.toArray(new Predicate[predicatesList.size()]));
				return null;
			}
		};
		return storeForwardRepository.findAll(spec, pageable);
	}
	
	@RequestMapping(value = "/countStoreForward", produces = "application/json")
	public Page<StoreForward> countStoreForward(String fieldId, String systemId,
			String ifName, String beginDate,String endDate,String status, Pageable pageable) {
		User user = userSessionService.getCurrentAuthenticatedUser();
		String userId = user.getId();
		if (fieldId == null) {
			fieldId = "";
		}
		if (systemId == null) {
			systemId = "";
		}
		if (ifName == null) {
			ifName = "";
		} else {
			ifName = "%" + ifName + "%";
		}
		if (beginDate == null) {
			beginDate = "1999-01-01 00:00:00";
		} 
		if (endDate == null) {
			endDate = "2999-01-01 00:00:00";
		}
		if(status==null){
			status="";
		}
		int page1, page2;

		page1 = pageable.getPageNumber()*pageable.getPageSize();
		page2 = pageable.getPageSize();

		List<Object[]> storeForwards = storeForwardRepository.countStoreForward(userId, fieldId, systemId, ifName, beginDate, endDate, status, page1, page2);
		List<Object[]> totalStoreForwards = storeForwardRepository.totalCountStoreForward(userId, fieldId, systemId, ifName, beginDate, endDate, status);
		List<StoreForward> result = new ArrayList<StoreForward>(totalStoreForwards.size());
		int total = totalStoreForwards.size();
		for (Object[] storeForward : storeForwards) {
			StoreForward storeForward1 = new StoreForward();
			storeForward1.setField(storeForward[0] != null ? (String) storeForward[0]: "");
			storeForward1.setFieldId(storeForward[1] != null ? (String) storeForward[1]: "");
			storeForward1.setSystemId(storeForward[2] != null ? (String) storeForward[2] : "");
			storeForward1.setSystemName(storeForward[3] != null ? (String) storeForward[3] : "");
			storeForward1.setInterfaceName(storeForward[4] != null ? (String) storeForward[4]: "");
			if(StringUtils.equals(storeForward[5].toString(), ForwardStatus.FORWARDFAILD.ValueCode)){
				storeForward1.setForwardState(storeForward[5] != null ? "转发失败": "");
			}
			if(StringUtils.equals(storeForward[5].toString(), ForwardStatus.FORWARDING.ValueCode)){
				storeForward1.setForwardState(storeForward[5] != null ? "正在转发": "");
			}
			if(StringUtils.equals(storeForward[5].toString(), ForwardStatus.FORWARDSUCCESS.ValueCode)){
				storeForward1.setForwardState(storeForward[5] != null ? "转发成功": "");
			}
			String num6 = storeForward[6].toString();
			int num=Integer.parseInt(num6);
			storeForward1.setTotalTime(storeForward[6] != null ? num : 0);
			result.add(storeForward1);
		}
		Page<StoreForward> page3 = new PageImpl<StoreForward>(result, pageable, total);
		return page3;
	}
	
}